/* eslint-disable */
<template>
  <div class="classes-container">
    <!-- 欢迎信息 -->
    <div class="welcome-section">
      <h2>{{ greeting }}，{{ userInfo.name }}</h2>
      <p class="subtitle">今天是 {{ currentDate }}，{{ motivationalQuote }}</p>
    </div>

    <!-- 课程导航 -->
    <div class="nav-section">
      <el-tabs v-model="activeTab">
        <el-tab-pane label="我的课程" name="courses">
          <!-- <div class="add-course-btn">
            <el-button type="primary" icon="el-icon-plus" @click="showAddCourseDialog">创建课程</el-button>
          </div> -->
          <div v-if="loading" class="loading-container">
            <el-skeleton :rows="3" animated />
          </div>
          <el-empty v-else-if="courses.length === 0" description="暂无课程"></el-empty>
          <el-row v-else :gutter="20">
            <el-col :span="6" v-for="course in courses" :key="course.id">
              <el-card class="course-card" shadow="hover" @click.native="goCourseDetail(course)">
                <div class="course-cover">
                  <img :src="require('@/assets/' + course.image)" :alt="course.name">
                </div>
                <div class="course-info">
                  <h3>{{ course.name }}</h3>
                  <p class="course-class">{{ course.className }}</p>
                  <p class="course-time">{{ course.time }}</p>
                  <div class="course-stats">
                    <el-tooltip content="学生人数" placement="top">
                      <span><i class="el-icon-user"></i> {{ course.studentCount }}</span>
                    </el-tooltip>
                    <el-tooltip content="待批改作业" placement="top">
                      <span><i class="el-icon-edit-outline"></i> {{ course.pendingHomework }}</span>
                    </el-tooltip>
                  </div>
                </div>
              </el-card>
            </el-col>
          </el-row>
        </el-tab-pane>
        <el-tab-pane label="系统公告" name="announcement">
          <div v-if="announcementLoading" class="loading-container">
            <el-skeleton :rows="3" animated />
          </div>
          <el-empty v-else-if="announcements.length === 0" description="暂无公告"></el-empty>
          <div v-else class="announcement-list">
            <div v-for="(notice, index) in announcements" :key="index" class="announcement-item">
              <div class="announcement-header">
                <h4>{{ notice.title }}</h4>
                <span class="time">{{ formatDate(notice.createTime) }}</span>
              </div>
              <p class="content">{{ notice.content }}</p>
            </div>
          </div>
        </el-tab-pane>
      </el-tabs>
    </div>

    <!-- 创建课程对话框 -->
    <el-dialog title="创建课程" :visible.sync="courseDialog.visible" width="40%">
      <el-form :model="courseForm" :rules="courseRules" ref="courseForm" label-width="80px">
        <el-form-item label="课程名称" prop="name">
          <el-input v-model="courseForm.name"></el-input>
        </el-form-item>
        <el-form-item label="班级" prop="className">
          <el-input v-model="courseForm.className"></el-input>
        </el-form-item>
        <el-form-item label="学期" prop="time">
          <el-select v-model="courseForm.time" placeholder="请选择学期" style="width: 100%">
            <el-option label="2024春季学期" value="2024春季学期"></el-option>
            <el-option label="2024秋季学期" value="2024秋季学期"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="上课时间" prop="schedule">
          <el-input v-model="courseForm.schedule" placeholder="例如：周一 1-2节"></el-input>
        </el-form-item>
        <el-form-item label="上课地点" prop="location">
          <el-input v-model="courseForm.location"></el-input>
        </el-form-item>
        <el-form-item label="课程简介" prop="description">
          <el-input type="textarea" v-model="courseForm.description" :rows="3"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="courseDialog.visible = false">取 消</el-button>
        <el-button type="primary" @click="handleCreateCourse">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { getTeacherCourses, createCourse, getSystemAnnouncements } from '@/api/teacher'

export default {
  name: 'TeacherClasses',
  data() {
    return {
      userInfo: JSON.parse(localStorage.getItem('userInfo') || '{}'),
      activeTab: 'courses',
      loading: false,
      announcementLoading: false,
      courses: [],
      announcements: [],
      courseDialog: {
        visible: false
      },
      courseForm: {
        name: '',
        className: '',
        time: '',
        schedule: '',
        location: '',
        description: ''
      },
      courseRules: {
        name: [
          { required: true, message: '请输入课程名称', trigger: 'blur' }
        ],
        className: [
          { required: true, message: '请输入班级', trigger: 'blur' }
        ],
        time: [
          { required: true, message: '请选择学期', trigger: 'change' }
        ],
        schedule: [
          { required: true, message: '请输入上课时间', trigger: 'blur' }
        ],
        location: [
          { required: true, message: '请输入上课地点', trigger: 'blur' }
        ]
      }
    }
  },
  computed: {
    greeting() {
      const hour = new Date().getHours()
      if (hour < 6) return '凌晨好'
      if (hour < 9) return '早上好'
      if (hour < 12) return '上午好'
      if (hour < 14) return '中午好'
      if (hour < 17) return '下午好'
      if (hour < 19) return '傍晚好'
      return '晚上好'
    },
    currentDate() {
      const date = new Date()
      return `${date.getFullYear()}年${date.getMonth() + 1}月${date.getDate()}日`
    },
    motivationalQuote() {
      const quotes = [
        '教育是一门艺术',
        '用心育人，静待花开',
        '教学相长，共同进步',
        '春风化雨，润物无声'
      ]
      return quotes[Math.floor(Math.random() * quotes.length)]
    }
  },
  created() {
    // 加载教师课程数据
    this.loadCourses()
    
    // 监听标签页变化，加载不同数据
    this.$watch('activeTab', (newValue) => {
      if (newValue === 'announcement' && this.announcements.length === 0) {
        this.loadAnnouncements()
      }
    })
  },
  methods: {
    // 加载教师课程
    loadCourses() {
      this.loading = true
      
      getTeacherCourses(this.userInfo.teacherId)
        .then(response => {
          if (response.code === 200) {
            this.courses = response.data
          } else {
            this.$message.error(response.msg || '获取课程列表失败')
          }
        })
        .catch(error => {
          console.error('获取课程列表错误:', error)
          this.$message.error('获取课程列表异常，请稍后重试')
        })
        .finally(() => {
          this.loading = false
        })
    },
    
    // 加载系统公告
    loadAnnouncements() {
      this.announcementLoading = true
      
      getSystemAnnouncements()
        .then(response => {
          if (response.code === 200) {
            this.announcements = response.data
            if (this.announcements.length === 0) {
              this.$message.info('暂无系统公告')
            }
          } else {
            this.$message.error(response.msg || '获取公告失败')
          }
        })
        .catch(error => {
          console.error('获取公告错误:', error)
          this.$message.error('获取公告异常，请稍后重试')
        })
        .finally(() => {
          this.announcementLoading = false
        })
    },
    
    // 查看课程详情
    goCourseDetail(course) {
      this.$router.push({
        path: `/teacher/course/${course.id}`,
        query: { classId: course.classId }
      })
    },
    
    // 显示添加课程对话框
    showAddCourseDialog() {
      this.courseForm = {
        name: '',
        className: '',
        time: '',
        schedule: '',
        location: '',
        description: ''
      }
      this.courseDialog.visible = true
    },
    
    // 创建课程
    handleCreateCourse() {
      this.$refs.courseForm.validate(valid => {
        if (valid) {
          // 添加教师ID
          const courseData = {
            ...this.courseForm,
            teacherId: this.userInfo.teacherId
          }
          
          createCourse(courseData)
            .then(response => {
              if (response.code === 200) {
                this.$message.success('课程创建成功')
                this.courseDialog.visible = false
                this.loadCourses() // 重新加载课程列表
              } else {
                this.$message.error(response.msg || '创建课程失败')
              }
            })
            .catch(error => {
              console.error('创建课程错误:', error)
              this.$message.error('创建课程异常，请稍后重试')
            })
        }
      })
    },
    
    // 格式化日期
    formatDate(dateStr) {
      if (!dateStr) return ''
      try {
        const dateObj = new Date(dateStr)
        if (isNaN(dateObj.getTime())) {
          return dateStr // 如果日期无效，则返回原始字符串
        }
        return `${dateObj.getFullYear()}-${String(dateObj.getMonth() + 1).padStart(2, '0')}-${String(dateObj.getDate()).padStart(2, '0')} ${String(dateObj.getHours()).padStart(2, '0')}:${String(dateObj.getMinutes()).padStart(2, '0')}`
      } catch (e) {
        console.error('日期格式化错误:', e)
        return dateStr // 发生错误时返回原始字符串
      }
    }
  }
}
</script>

<style scoped>
.classes-container {
  padding: 20px;
  background-color: #f0f2f5;
  min-height: calc(100vh - 60px);
}

.welcome-section {
  margin-bottom: 30px;
  padding: 20px;
  background: white;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0,0,0,0.1);
}

.welcome-section h2 {
  margin: 0;
  color: #303133;
}

.subtitle {
  margin: 10px 0 0;
  color: #909399;
}

.nav-section {
  background: white;
  padding: 20px;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0,0,0,0.1);
}

.add-course-btn {
  margin-bottom: 20px;
  text-align: right;
}

.loading-container {
  padding: 20px;
}

.course-card {
  margin-bottom: 20px;
  cursor: pointer;
  transition: all 0.3s;
}

.course-card:hover {
  transform: translateY(-5px);
}

.course-cover {
  height: 160px;
  overflow: hidden;
  border-radius: 4px;
}

.course-cover img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.course-info {
  padding: 15px 0;
}

.course-info h3 {
  margin: 0 0 10px;
  font-size: 16px;
  color: #303133;
}

.course-info p {
  margin: 5px 0;
  font-size: 13px;
  color: #909399;
}

.course-stats {
  margin-top: 15px;
  display: flex;
  justify-content: space-between;
  color: #606266;
  font-size: 13px;
}

.course-stats span {
  display: flex;
  align-items: center;
}

.course-stats i {
  margin-right: 4px;
}

.announcement-list {
  padding: 0 20px;
}

.announcement-item {
  padding: 20px 0;
  border-bottom: 1px solid #EBEEF5;
}

.announcement-item:last-child {
  border-bottom: none;
}

.announcement-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 10px;
}

.announcement-header h4 {
  margin: 0;
  color: #303133;
  font-size: 16px;
}

.announcement-header .time {
  color: #909399;
  font-size: 13px;
}

.announcement-item .content {
  margin: 0;
  color: #606266;
  line-height: 1.6;
}
</style> 